package com.algorithm.liyc.echa;

import com.algorithm.liyc.entity.TreeNode;

import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 0513.找树左下角的值
 * 给定一个二叉树，在树的最后一行找到最左边的值。
 *
 * @author Liyc
 * @date 2024/1/8 17:29
 **/

public class Solution12 {
    private int Depth = -1;
    private int result = 0;

    /**
     * 递归法
     * @param root
     * @return
     */
    public int findBottomLeftValue1(TreeNode root) {
        result = root.val;
        findLeftValue(root, 0);
        return result;
    }
    public void findLeftValue(TreeNode root, int deep) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            if (deep > Depth) {
                result = root.val;
                Depth = deep;
            }
        }
        if (root.left != null) findLeftValue(root.left, deep + 1);
        if (root.right != null) findLeftValue(root.right, deep + 1);
    }

    /**
     * 迭代法
     * @param root
     * @return
     */
    public int findBottomLeftValue2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int result = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode treeNode = queue.poll();
                if (i == 0) {
                    result = treeNode.val;
                }
                if (treeNode.left != null) queue.offer(treeNode.left);
                if (treeNode.right != null) queue.offer(treeNode.right);
            }
        }
        return result;
    }
}
